package com.etone.smartAudit.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.ItemServerPath;
import com.etone.smartAudit.domain.ServerPath;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.ItemServerPathMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author: sovy
 * @date: 2020/11/24
 * @description:
 */

@Service
public class ItemServerPathService extends ServiceImpl<ItemServerPathMapper, ItemServerPath> {

    @Autowired
    private ServerPathService serverPathService;

    /**
     * 查看用户是有权限操作该文件
     *
     * @param admin
     * @param itemId
     * @param serverId
     * @param path
     * @return true有权限，false无权限
     */
    public boolean hasAuth(Admin admin, Integer itemId, Integer serverId, String path) {
        if (admin.isAdmin()) {
            return baseMapper.hasAuth(null, null, serverId, path);
        }
        return baseMapper.hasAuth(admin.getId(), itemId, serverId, path);
    }

    /**
     * 查看用户是有权限操作该文件,并抛出异常
     *
     * @param admin
     * @param itemId
     * @param serverId
     * @param path
     */
    public void hasAuthThrow(Admin admin, Integer itemId, Integer serverId, String path) {
        if (!hasAuth(admin, itemId, serverId, path)) {
            throw new CustomParameterizedException("您没有权限操作");
        }
    }

    /**
     * 增加路径
     *
     * @param itemId
     * @param serverId
     * @param path
     * @param space
     */
    public void add(Integer itemId, Integer serverId, String path, Double space) {
        if (itemId == null || serverId == null || StringUtils.isEmpty(path) || space == null) {
            return;
        }
        //获取路径id
        Integer serverPathId = serverPathService.findId(serverId, path);
        if (serverPathId == null) {
            ServerPath serverPath = ServerPath.builder().path(path).serverId(serverId).space(space).build();
            serverPathService.save(serverPath);
            serverPathId = serverPath.getId();
        } else {
            //判断是否存在
            boolean hasItemServerPath = baseMapper.hasItemServerPath(itemId, serverPathId);
            if (hasItemServerPath) {
                return;
            }
        }
        if (serverPathId == null) {
            throw new CustomParameterizedException("服务器路径不存在");
        }
        save(ItemServerPath.builder().itemId(itemId).serverPathId(serverPathId).build());

    }
}
